package com.sl.utils.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author : zhouxd
 * @date : 2019/12/31 10:31
 */
public class JacksonUtils {

    private static ObjectMapper objectMapper;
    private static String dateTimeFormatterStr = "yyyy-MM-dd HH:mm:ss";
    private static String dateFormatterStr = "yyyy-MM-dd ";
    private static String timeFormatterStr = "yyyy-MM-dd ";


    /**
     * 返回自定义的时间格式化mapper
     *
     * @return
     */
    public static ObjectMapper getCustomObjectMapper() {
        if (null != objectMapper) {
            return objectMapper;
        } else {
            objectMapper = new ObjectMapper();
            JavaTimeModule timeModule = new JavaTimeModule();
            timeModule.addSerializer(LocalDateTime.class,
                    new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormatterStr)));
            timeModule.addSerializer(LocalDate.class,
                    new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormatterStr)));
            timeModule.addSerializer(LocalTime.class,
                    new LocalTimeSerializer(DateTimeFormatter.ofPattern(timeFormatterStr)));
            objectMapper.registerModule(timeModule);
            return objectMapper;
        }

    }
    /**
     * 返回自定义的时间格式化mapper 反序列化
     *
     * @return
     */
    public static ObjectMapper getCustomObjectMapperAddDeserializer() {
        if (null != objectMapper) {
            return objectMapper;
        } else {
            objectMapper = new ObjectMapper();
            JavaTimeModule timeModule = new JavaTimeModule();
            timeModule.addDeserializer(LocalDateTime.class,
                    new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateTimeFormatterStr)));
            timeModule.addDeserializer(LocalDate.class,
                    new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormatterStr)));
            timeModule.addDeserializer(LocalTime.class,
                    new LocalTimeDeserializer(DateTimeFormatter.ofPattern(timeFormatterStr)));
            objectMapper.registerModule(timeModule);
            return objectMapper;
        }

    }

}
